from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import List, Optional

from app.db.database import get_db
from app.core.security import get_current_user, get_current_active_user
from app.schemas.merchant import (
    Merchant, MerchantCreate, MerchantUpdate, 
    MerchantBrief, MerchantImage, MerchantImageCreate
)
from app.crud import merchant as merchant_crud

router = APIRouter()


@router.get("/", response_model=List[MerchantBrief])
async def read_merchants(
    skip: int = 0,
    limit: int = 100,
    name: Optional[str] = None,
    is_verified: Optional[bool] = Query(None),
    is_active: Optional[bool] = Query(None),
    db: Session = Depends(get_db)
):
    """获取商家列表"""
    merchants = merchant_crud.get_merchants(
        db, 
        skip=skip, 
        limit=limit, 
        name=name,
        is_verified=is_verified,
        is_active=is_active
    )
    return merchants


@router.post("/", response_model=Merchant)
async def create_merchant(
    merchant: MerchantCreate,
    current_user: dict = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """创建商家"""
    # 检查用户是否已经是商家
    existing_merchant = merchant_crud.get_merchant_by_user_id(db, current_user["id"])
    if existing_merchant:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="您已经是商家，不能重复申请"
        )
    
    # 创建商家
    return merchant_crud.create_merchant(db, merchant, current_user["id"])


@router.get("/me", response_model=Merchant)
async def read_my_merchant(
    current_user: dict = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取当前用户的商家信息"""
    merchant = merchant_crud.get_merchant_by_user_id(db, current_user["id"])
    if not merchant:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="您还不是商家"
        )
    return merchant


@router.get("/{merchant_id}", response_model=Merchant)
async def read_merchant(
    merchant_id: int,
    db: Session = Depends(get_db)
):
    """获取商家详情"""
    merchant = merchant_crud.get_merchant(db, merchant_id)
    if not merchant:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="商家不存在"
        )
    return merchant


@router.put("/{merchant_id}", response_model=Merchant)
async def update_merchant(
    merchant_id: int,
    merchant_update: MerchantUpdate,
    current_user: dict = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """更新商家信息"""
    # 检查是否是本人或管理员
    merchant = merchant_crud.get_merchant(db, merchant_id)
    if not merchant:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="商家不存在"
        )
    
    if merchant.user_id != current_user["id"] and current_user.get("role") != "admin":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限修改此商家信息"
        )
    
    # 更新商家信息
    updated_merchant = merchant_crud.update_merchant(db, merchant_id, merchant_update)
    return updated_merchant


@router.delete("/{merchant_id}", response_model=dict)
async def delete_merchant(
    merchant_id: int,
    current_user: dict = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """删除商家（软删除）"""
    # 检查是否是本人或管理员
    merchant = merchant_crud.get_merchant(db, merchant_id)
    if not merchant:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="商家不存在"
        )
    
    if merchant.user_id != current_user["id"] and current_user.get("role") != "admin":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限删除此商家"
        )
    
    # 删除商家
    merchant_crud.delete_merchant(db, merchant_id)
    return {"status": "success", "message": "商家已删除"}


@router.put("/{merchant_id}/verify", response_model=Merchant)
async def verify_merchant(
    merchant_id: int,
    is_verified: bool,
    current_user: dict = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """验证/取消验证商家（管理员操作）"""
    # 检查是否是管理员
    if current_user.get("role") != "admin":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有管理员可以执行此操作"
        )
    
    # 验证商家
    merchant = merchant_crud.verify_merchant(db, merchant_id, is_verified)
    if not merchant:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="商家不存在"
        )
    
    return merchant


@router.post("/{merchant_id}/images", response_model=MerchantImage)
async def create_merchant_image(
    merchant_id: int,
    image: MerchantImageCreate,
    current_user: dict = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """添加商家图片"""
    # 检查是否是本人
    merchant = merchant_crud.get_merchant(db, merchant_id)
    if not merchant:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="商家不存在"
        )
    
    if merchant.user_id != current_user["id"] and current_user.get("role") != "admin":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限为此商家添加图片"
        )
    
    # 添加图片
    db_image = merchant_crud.create_merchant_image(db, merchant_id, image)
    return db_image


@router.delete("/{merchant_id}/images/{image_id}", response_model=dict)
async def delete_merchant_image(
    merchant_id: int,
    image_id: int,
    current_user: dict = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """删除商家图片"""
    # 检查是否是本人
    merchant = merchant_crud.get_merchant(db, merchant_id)
    if not merchant:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="商家不存在"
        )
    
    if merchant.user_id != current_user["id"] and current_user.get("role") != "admin":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限删除此商家图片"
        )
    
    # 删除图片
    result = merchant_crud.delete_merchant_image(db, image_id)
    if not result:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="图片不存在"
        )
    
    return {"status": "success", "message": "图片已删除"} 